package com.ctrip.framework.apollo.spring.spi;

import com.ctrip.framework.apollo.core.spi.Ordered;
import com.ctrip.framework.apollo.spring.annotation.ApolloAnnotationProcessor;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValueProcessor;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor;
import com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor;
import com.ctrip.framework.apollo.spring.util.BeanRegistrationUtil;
import com.google.common.collect.Lists;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * spring的默认apollo配置注册帮助类
 */
public class DefaultApolloConfigRegistrarHelper implements ApolloConfigRegistrarHelper {

  @Override
  public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    // 获取apollo注解上的属性
    AnnotationAttributes attributes = AnnotationAttributes
        .fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
    // 获取命名空间 和 order顺序
    String[] namespaces = attributes.getStringArray("value");
    int order = attributes.getNumber("order");
    PropertySourcesProcessor.addNamespaces(Lists.newArrayList(namespaces), order);
    Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>();
    // 赋值@Order(0),确保执行优先  to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer
    propertySourcesPlaceholderPropertyValues.put("order", 0);

    // 接下来注册N个bean PropertySourcesPlaceholderConfigurer占位符处理器，spring自带的类
    BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
        PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues);
    // PropertySourcesProcessor：配置初始化(里面还提供了属性自动更新的onChange方法)
    // -- 用来实现属性动态加载关键（实现了BeanFactoryPostProcessor、EnvironmentAware、PriorityOrdered）
    BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
        PropertySourcesProcessor.class);
    // ================以下类均实现了ApolloProcessor==================================
    // ==========================里面有postProcessBeforeInitialization、postProcessAfterInitialization，
    // ==========================里面采用模板方法模式，下面只需要实现对应模板方法processField()、processMethod()即可
    // - 1 通过反射获取注解@ApolloConfig，并解析获取值，然后反射注入对应的bean的field
    // - 2 将声明了@ApolloConfigChangeListener注解的方法添加进对应命名空间Namespace的配置中
    BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class.getName(),
        ApolloAnnotationProcessor.class);
    // - 1 解析被@Value声明的field和method,然后把bean和键值等信息包装放到SpringValueRegistry中
    BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class.getName(),
        SpringValueProcessor.class);
    // - 1 找出所有的bean映射的value信息，并存储在springValueDefinitions。举个例子：mybatis的初始化类里面的参数跟xml映射的属性,会在mybatis.xml里面配置了对应的配置类地址
    BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class.getName(),
        SpringValueDefinitionProcessor.class);
    // - 1 扫描所有注解，并加载赋值进去。这个注解作用是可以更方便解析json
        //    @ApolloJsonValue("${someJsonPropertyKey:{\"someString\":\"someDefaultValue\", \"someInt\":10}}")
        //    private SomeObject someObject;
    BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloJsonValueProcessor.class.getName(),
        ApolloJsonValueProcessor.class);
  }

  @Override
  public int getOrder() {
    return Ordered.LOWEST_PRECEDENCE;
  }
}
